﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Planer.Model.Validators;

namespace Planer.Model
{
    public class ActionCategoryModel
    {
        static ActionCategoryModel model = null;

        protected ActionCategoryModel()
        {            
        }

        public static ActionCategoryModel GetInstance()
        {
            if (model == null)
            {
                model = new ActionCategoryModel();
            }

            return model;
        }

        public static readonly string TRANSFER_ACTION_CATEGORY_NAME = "Перевод средств";

        public action_category GetTransferActionCategory()
        {
            var query = from act in Program.Db.action_category
                        where act.name == TRANSFER_ACTION_CATEGORY_NAME
                        select act;
            if (query.Count<action_category>() == 0)
            {
                action_category cat = new action_category()
                {
                    name = TRANSFER_ACTION_CATEGORY_NAME
                };
                ModelResult mr = SaveOrUpdateActionCategory(cat);
                if (mr.Status == OperationStatusType.ERROR)
                {
                    throw new Exception(mr.ShowAllMessages);
                }
                return cat;
            }
            return query.First<action_category>();
        }

        public ModelResult SaveOrUpdateActionCategory(action_category ActionCategory)
        {
            ActionCategoryValidator validator = new ActionCategoryValidator();
            validator.Validate(ActionCategory);
            if (validator.Status == OperationStatusType.ERROR)
            {
                return new ModelResult(validator.Errors);
            }

            if (ActionCategory.id == 0)
            {
                Program.Db.AddToaction_category(ActionCategory);
            }
            if (Program.Db.SaveChanges() == 1)
            {
                return new ModelResult();
            }
            return new ModelResult("Ошибка сохранения категории действия");
        }

        public List<action_category> GetActionCategoryList()
        {
            List<action_category> categories = new List<action_category>();
            var query = from act in Program.Db.action_category
                        orderby act.name
                        where act.name != TRANSFER_ACTION_CATEGORY_NAME
                        select act;
            categories.AddRange(query.ToList<action_category>());
           
            return categories;
        }
    }
}
